package com.linkin.homepage.ui.home.exam;

import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.linkin.homepage.R;
import com.linkin.homepage.base.BaseFragment;
import com.linkin.homepage.base.recycleview.RCWrapperAdapter;
import com.linkin.homepage.base.recycleview.RecyclerViewUtils;
import com.linkin.homepage.base.rxbase.RxManager;
import com.linkin.homepage.base.util.Predictor;
import com.linkin.homepage.base.viewmapping.ViewMapping;
import com.linkin.homepage.bean.BannerBean;
import com.linkin.homepage.bean.ClassItemBean;
import com.linkin.homepage.bean.ExamDataBean;
import com.linkin.homepage.ui.adapter.ComRCAdapter;
import com.linkin.homepage.ui.adapter.ImageAdapter;
import com.linkin.homepage.ui.home.ComListHelper;
import com.linkin.homepage.ui.home.OnReClickListener;
import com.linkin.homepage.ui.home.homeclass.ClassFragment;
import com.linkin.homepage.util.ToastUitl;
import com.linkin.homepage.view.AttachView;
import com.linkin.homepage.view.PagerSlidingTabStrip;
import com.linkin.homepage.view.refresh.RefreshFooterState;
import com.linkin.homepage.view.refresh.RefreshViewUtils;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerAdapter;
import com.youth.banner.listener.OnBannerListener;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

@ViewMapping(R.layout.fragment_content)
public class ExamFragment extends BaseFragment implements ExamContract.View, OnReClickListener {

    private static final String TAG = "ExamFragment";

    RecyclerView mRecyclerView;

    private String mExamId;
    private String mTitle;
    private ComRCAdapter mNewsAdapter;
    private RxManager mRxManager;
    private ExamPresenter mPresenter;

    private Banner mBanner;
    private BannerAdapter mBannerAdapter;
    private List<BannerBean> mBannerList = new ArrayList<>();
    private ExamDataBean mHomeInfo = null;

    //底部ViewPager
    ViewPager2 mViewPager;
    PagerSlidingTabStrip mPagerSlidingTabStrip;
    ClassPagerAdapter mPagerAdapter;

    private final ArrayList<String> mClassTitleList = new ArrayList<>();
    private final SparseArray<Fragment> mFragmentList = new SparseArray<>();

    public static ExamFragment newInstance(String examId, String title) {
        ExamFragment fragment = new ExamFragment();
        fragment.mExamId = examId;
        fragment.mTitle = title;
        return fragment;
    }

    @Override
    protected String getFragmentTag() {
        return "ExamFragment";
    }

    @Override
    protected void initView(View rootView) {
        initPresenter();
        initRxManager();
        initRecyclerView();
        initBanner();
        initViewPager();
    }

    private void initPresenter() {
        mPresenter = new ExamPresenter(this, mExamId);
    }

    private void initRxManager() {
        mRxManager = new RxManager();
//        mRxManager.on(EventBusConstants.FOCUS_AUTHORS_EVENT, (Consumer<String>) s -> {
//            if (isAlive()) {
//                mRecyclerView.scrollToPosition(0);
//                mPresenter.subscribe();
//            }
//        });
    }

    private void initRecyclerView() {
        mRecyclerView = getRootView().findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        mNewsAdapter = new ComRCAdapter(mContext);
        mNewsAdapter.setRxManager(mRxManager);
        mRecyclerView.setAdapter(new RCWrapperAdapter(mNewsAdapter));

        RefreshViewUtils.setOnRefreshListener(mRecyclerView, this::onRefresh);
    }

    /**
     * ViewPager
     */
    private void initViewPager() {
        mViewPager = getRootView().findViewById(R.id.second_view_pager);
        mPagerSlidingTabStrip = getRootView().findViewById(R.id.pager_sliding_tab_strip_two);

        mPagerAdapter = new ClassPagerAdapter(this);
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setOffscreenPageLimit(1);

        mPagerSlidingTabStrip.setViewPager(mViewPager);
        mPagerSlidingTabStrip.setLeftInterpolator(new AccelerateInterpolator(1.2f));
        mPagerSlidingTabStrip.setRightInterpolator(new DecelerateInterpolator(1.2f));
    }

    @Override
    protected void clear() {
        mBanner.stop();
        mRxManager.clear();
        mPresenter.unsubscribe();
    }

    @Override
    public void showError(boolean refresh) {
        if (isAlive()) {
            if (refresh) {
                RefreshViewUtils.onRefreshComplete(mRecyclerView);
                if ((mNewsAdapter == null || mNewsAdapter.getItemCount() == 0)) {
                    showFailed();
                    ToastUitl.showShort("请求数据失败，请重试");
                } else {
                    showNormal();
                }
            }
        }
    }

    //下拉刷新调用方法
    private void onRefresh(boolean isGesture) {
        mPresenter.subscribe(isGesture);
    }

    //添加初始化Banner,并添加到顶部
    private void initBanner() {
        View headerView = LayoutInflater.from(getContext()).inflate(R.layout.layout_news_header, mRecyclerView, false);
        mBanner = headerView.findViewById(R.id.banner);
        mBannerAdapter = new ImageAdapter(mBannerList);
        mBanner.setAdapter(mBannerAdapter, true);
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(Object data, int position) {
                ToastUitl.show("点击Banner", Toast.LENGTH_SHORT);
            }
        });

        AttachView attachView = headerView.findViewById(R.id.attach_view);
        attachView.setWindowAttachListener(new ViewTreeObserver.OnWindowAttachListener() {
            @Override
            public void onWindowAttached() {
                mBanner.start();
                getHandler().postDelayed(() -> mBanner.getViewPager2().requestLayout(), 0);
            }

            @Override
            public void onWindowDetached() {
                if (isAlive()) {
                    mBanner.stop();
                    ViewPager2 viewPager2 = mBanner.getViewPager2();
                    if (viewPager2 != null) {
                        RecyclerView.Adapter pagerAdapter = viewPager2.getAdapter();
                        if (pagerAdapter != null) {
                            int index = viewPager2.getCurrentItem();
                            int count = pagerAdapter.getItemCount();
                            if (count >= 3 && index >= count - 1) {
                                viewPager2.setCurrentItem(1, false);
                            }
                        }
                    }

                }
            }
        });

        RecyclerViewUtils.setHeaderView(mRecyclerView, headerView);
    }

    @Override
    protected void initData() {
        showLoading();
        onRefresh(false);
    }

    @Override
    protected void refreshData() {
        if (isAlive()) {
            ComListHelper.refreshData(this, mRecyclerView, mNewsAdapter);
        }
    }

    @Override
    public void onReClick() {
        refreshData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser
                && isAlive()
                && mNewsAdapter.getItemCount() == 0
                && !RefreshViewUtils.isRefreshing(mRecyclerView)) {
            refreshData();
        }
    }

    /**
     * 下拉刷新（）
     */
    @Override
    public void showNewsHome(ExamDataBean homeInfo) {
        if (isFragmentDestroyed() || homeInfo == null) {
            return;
        }

        mHomeInfo = homeInfo;
        RefreshViewUtils.onRefreshComplete(mRecyclerView);
        showNormal();
        //显示Banner数据
        showBanners(homeInfo.getBanners());

        //显示底部ViewPager的Title
        showClassItems(homeInfo.getClass_items());

        RefreshViewUtils.onLoadMoreComplete(mRecyclerView, RefreshFooterState.GONE);
    }

    /**
     * Banner数据根系
     */
    private void showBanners(List<BannerBean> beanList) {
        if (beanList == null || Predictor.isEmpty(beanList)) {
            return;
        }
        mBannerList.clear();
        mBannerList.addAll(beanList);

        mBannerAdapter.setDatas(mBannerList);
        mBanner.start();
    }

    private void showClassItems(List<ClassItemBean> classItemBeanList) {
        if (classItemBeanList == null || Predictor.isEmpty(classItemBeanList)) {
            return;
        }

        mClassTitleList.clear();
        for (ClassItemBean itemBean : classItemBeanList) {
            mClassTitleList.add(itemBean.getClass_name());
        }

        mPagerSlidingTabStrip.setTitleList(mClassTitleList);
        mPagerAdapter.notifyDataSetChanged();
    }


    private class ClassPagerAdapter extends FragmentStateAdapter {

        public ClassPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }

        public ClassPagerAdapter(@NonNull Fragment fragment) {
            super(fragment);
        }

        public ClassPagerAdapter(@NonNull FragmentManager fragmentManager, @NotNull Lifecycle lifecycle) {
            super(fragmentManager, lifecycle);
        }

        @NotNull
        @Override
        public Fragment createFragment(int position) {
            Fragment fragment = ClassFragment.newInstance(mExamId);
            if (!getUserVisibleHint()) {
                fragment.setUserVisibleHint(false);
            }
            mFragmentList.put(position, fragment);
            return fragment;
        }

        @Override
        public int getItemCount() {
            return mClassTitleList.size();
        }
    }
}
